<?php

namespace App\Kuafu\Banner\Model;

use App\Kuafu\Banner\Enum\BannerEnum;
use App\Kuafu\Base\Model\BaseModel;
use App\Kuafu\Base\Model\Traits\KfSoftDeletes;
use App\Kuafu\CouponPackage\Enum\CouponPackageEnum;
use App\Kuafu\Shop\Model\Shop;
use App\Kuafu\Shop\Enum\CodeEnum;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Relations\HasMany;

class BannerCommonModel extends BaseModel
{
    use KfSoftDeletes;

    protected $connection = 'mysql';
    protected $table      = 'banner';
    protected $primaryKey = 'id';


    const RESOURCE_TYPE_IMG   = 0;
    const RESOURCE_TYPE_VIDEO = 1;

    const RESOURCE_TYPE_TEXT = [
        self::RESOURCE_TYPE_IMG   => "图片",
        self::RESOURCE_TYPE_VIDEO => "视频"
    ];

    protected $hidden = [
        'updatedAt',
        'isDeleted'
    ];

    protected $appends = [
        'typeText',
    ];

    public function getTypeTextAttribute(): string
    {
        if ($this->type = BannerEnum::TYPE_BANNER) {
            return BannerEnum::BANNER_TYPE_MAPPING[$this->bannerType] ?? 'banner';
        }
        return BannerEnum::TYPE_MAP[$this->type];
    }

    /**
     * banner关联门店
     *
     * @return HasMany
     */
    public function bannerShopMappingRelate(): HasMany
    {
        return $this->hasMany(BannerCommonShopMappingsModel::class, 'bannerId', 'id');
    }

    /**
     * @param $pageSize
     * @param $pageNum
     * @param $name
     * @param $type
     * @param $status
     * @param int $shopId
     * @return LengthAwarePaginator
     */
    public static function getLists(
        $pageSize,
        $pageNum,
        $name,
        $type,
        $status,
        int $shopId
    ): LengthAwarePaginator {
        return self::query()
                   ->with([
                       'bannerShopMappingRelate' => function ($query) {
                           return $query->with([
                               'mappingShopRelate' => function ($query) {
                                   return $query->select(['id', 'name', 'shopCode']);
                               }
                           ]);
                       }
                   ])
                   ->when(strlen($name) > 0, function ($query) use ($name) {
                       $query->where('name', 'like', "%{$name}%");
                   })
                   ->when($shopId > 0, function ($query) use ($shopId) {
                       $shop = Shop::query()->where('id', $shopId)->first();
                       if ($shop) {
                           $query->where(function ($query) use ($shopId, $shop) {
                               $query
                                   ->whereHas('bannerShopMappingRelate',
                                       function ($query) use ($shopId) {
                                           $query->where('shopId', $shopId);
                                       })
                                   ->orWhere('shopType', '=', CouponPackageEnum::SHOP_TYPE_ALL)
                                   ->orWhere('shopType', '=', $shop->type);
                           });
                       } else {
                           $query->where('id', '=', 0);
                       }
                   })
                   ->when(strlen($type) > 0 && in_array($type, array_keys(BannerEnum::TYPE_MAP)),
                       function ($query) use ($type) {
                           $query->where('type', $type);
                       })
                   ->when(strlen($status) > 0 && in_array($status, array_keys(BannerEnum::STATUS_MAP)),
                       function ($query) use ($status) {
                           $query->where('status', $status);
                       })
                   ->orderBy('sort')
                   ->orderBy('id', 'desc')
                   ->paginate($pageSize, ['*'], 'page', $pageNum);
    }

    public static function getBannerByType(
        $type,
        $shopId,
        $shopType,
        $field,
        $selectType,
        $bannerType = BannerEnum::BANNER_TYPE_1
    ) {
        return self::query()
                   ->select($field)
                   ->where('type', $type)
                   ->when($type == BannerEnum::BANNER_TYPE_1, function ($query) use ($bannerType) {
                       $query->where('bannerType', $bannerType);
                   })
                   ->where('status', BannerEnum::STATUS_ON)
                   ->where(function ($query) {
                       $query->where('effectiveType', BannerEnum::EFFECTIVE_TYPE_ALWAYS)
                             ->orWhere(function ($query) {
                                 $query->where('startAt', '<=', time())
                                       ->where('endAt', '>=', time());
                             });
                   })
                   ->where(function ($query) use ($shopId, $shopType) {
                       $query->when($shopId, function ($query) use ($shopId, $shopType) {
                           $query->whereIn('shopType', [CodeEnum::SHOP_ALL, $shopType])
                                 ->orWhereHas('bannerShopMappingRelate', function ($query) use ($shopId) {
                                     $query->where('shopId', $shopId);
                                 });
                       });
                   })
                   ->orderBy('sort')
                   ->orderBy('createdAt', 'desc')
                   ->{$selectType}();
    }

    /**
     * 搜索
     * @param int $type
     * @param string $name
     * @return array
     */
    public static function bannerSearch(int $type, string $name = ''): array
    {
        $data = [];
        BannerCommonModel::query()
                         ->where('type', $type)
                         ->when($name, function ($query) use ($name) {
                             $query->where('name', 'like', "%{$name}%");
                         })
                         ->chunkById(100, function ($banner) use (&$data) {
                             foreach ($banner as $v) {
                                 if ($v['type'] == BannerEnum::TYPE_TV_MATERIAL_2) {//商屏素材—单品
                                     $imgs = json_decode($v->imgs, true);//默认图
                                     if (!$imgs) {
                                         continue;
                                     }
                                     foreach ($imgs as $img) {
                                         if (isset($img['price']) && $img['price'] == -1) {
                                             $data[] = [
                                                 'id'     => $v->id,
                                                 'name'   => $v->name,
                                                 'img'    => $img['img'],
                                                 'status' => $v->status,
                                             ];
                                             break;
                                         }
                                     }
                                 }
                             }
                         });
        return $data;
    }

}
